// packageE/picUpCard/picUpCardIndex/picUpCardIndex.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    agreement: false,
    promiseRadio: '1',
    addressName: "选择地区",
    addressShow: false,

    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    districtVal: [],
    districtFieldShow: false,
    districtPopupShow: false,

    provice: "",
    city: "",
    district: "",

    street: "选择街道",
    applyModel: {
      provinceId: "",
      cityId: "",
      districtId: "",
      streetId: "",
    },

    th_name: "",
    th_pass: "",
    th_mobile: "",
    th_address: "",
    promiseText: "输入提货密码查询",
    configInfo: {},
    goods_id: 0,
    goods_option_id: 0,
    th_pass_flag: false,

    pluginOptions: {
      plugin_name: "旅游激活卡",
      password_name: "激活密码",
      city_name: "出发城市",
      address_name: "出发地址"
    },
    plugin: "picking-card"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var info_arr = [];
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }

    if((options.plugin && options.plugin == "one") || info_arr.indexOf("plugin=one") !== -1) {
      //#78882，提货卡一期独立的新插件picking-card-one
      wx.setNavigationBarTitle({
        title: '提货卡'
      });
      let pluginOptions = {
        plugin_name: "提货卡",
        password_name: "提货密码",
        city_name: "所在城市",
        address_name: "收货地址"
      };
      this.setData({ 
        pluginOptions:pluginOptions,
        plugin: "picking-card-one"
      });
    }else{
      wx.setNavigationBarTitle({
        title: '旅游激活卡'
      });
    }
    this.getConfigInfo();

    this._initAddressInfo();
  },
  addressShowbtn() {
    this.setData({
      addressShow: true,
    });
  },

  getConfigInfo() {
    let _api = "plugin.picking-card.frontend.pickingCard.getConfig";
    if (this.data.plugin == "picking-card-one") _api = "plugin.picking-card-one.frontend.pickingCard.getConfig";
    let urlStr = app.getNetAddresss(_api);
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          res.data.is_show = Number(res.data.is_show);
          this.setData({
            configInfo: res.data,
          });
        }
      },
    });
  },
  selectPromisePrice() {
    let _api = "plugin.picking-card.frontend.pickingCard.getPrice";
    if (this.data.plugin == "picking-card-one") _api = "plugin.picking-card-one.frontend.pickingCard.getPrice";
    let urlStr = app.getNetAddresss(_api);
    app._getNetWork({
      url: urlStr,
      data: { password: this.data.th_pass },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) {
          console.log(res);
          this.setData({ th_pass_flag: false });
          return this.tips(res.msg);
        }
        this.setData({
          promiseText: res.data.margin,
          th_pass_flag: true,
          goods_id: res.data.goods_id,
          goods_option_id: res.data.goods_option_id
        });
      },
    });
  },
  send() {
    let {
      th_pass_flag,
      th_pass,
      th_name,
      th_mobile,
      districtFieldShow,
      applyModel,
      provice,
      city,
      district,
      street,
      th_address,
      promiseText,
      promiseRadio,
      goods_id,
      goods_option_id
    } = this.data;
    if (th_pass == "") return this.tips("提货密码不能为空");
    if (!th_pass_flag) return this.tips("提货密码错误");
    if (th_name == "") return this.tips("姓名不能为空");
    if (th_mobile == "") return this.tips("手机号不能为空");
    if (!applyModel.provinceId || !applyModel.cityId || !applyModel.districtId)
      return this.tips("请选择地区");
    if (districtFieldShow == true && !applyModel.streetId)
      return this.tips("请选择街道");
    if (th_address == "") return this.tips("收货地址不能为空");
    if (this.data.plugin == "picking-card-one" && this.data.promiseRadio == 0) return this.tips(`请选择是否使用${this.data.configInfo.commitment}兑换滤芯`);
    if (this.data.plugin == "picking-card-one" && !this.data.agreement) return this.tips("请勾选提货说明");
    console.log("发送请求");
    let address = {
      username: th_name,
      mobile: th_mobile,
      address: th_address,
      province: provice,
      city,
      district,
    };
    if (districtFieldShow == true) {
      address.street = street;
    }
    let _api = "plugin.picking-card.frontend.create.index";
    if (this.data.plugin == "picking-card-one") _api = "plugin.picking-card-one.frontend.create.index";

    let urlStr = app.getNetAddresss(_api);
    app._postNetWork({
      url: urlStr,
      data: {
        dispatch_type_id: 1,
        address: JSON.stringify(address),
        goods: JSON.stringify([{ goods_id, total: 1, option_id: goods_option_id }]),
        price: promiseText,
        password: this.data.th_pass,
        is_filter: Number(promiseRadio) - 1,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) {
          console.log(res);
          return this.tips(res.msg);
        }
        wx.redirectTo({
          url:
            "/packageD/buy/orderPay/orderPay?order_id=" +
            res.data.order_ids +
            "&status=2",
        });
        //packageD/buy/orderPay/orderPay
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  onChange(evt) {
    this.setData({
      agreement: evt.detail,
    });
  },
  onChangePromiseRadio(event) {
    this.setData({
      promiseRadio: event.detail,
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  streetShowbtn() {
    this.setData({
      districtPopupShow: true,
    });
  },
  treetShowLeft() {
    this.setData({
      districtPopupShow: false,
    });
  },
  streetConfirm(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      street: item.areaname,
      "applyModel.streetId": item.id,
      districtPopupShow: false,
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  setExplainFlag() {
    this.setData({
      explainFlag: !this.data.explainFlag,
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name":
            res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json,
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
        console.log("over", that.data.selectAddressData);
      },
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd: function () {
    let seleData = this.data.selectAddressData;
    let retCity =
      seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
    this.setData({
      addressName: retCity,
      provice: seleData[0].name,
      city: seleData[1].name,
      district: seleData[2].name,
    });
    this.setData({
      "applyModel.provinceId": seleData[0].id,
      "applyModel.cityId": seleData[1].id,
      "applyModel.districtId": seleData[2].id,
      addressShow: false,
    });
    this.getStreet(seleData[2].id);
  },
  //获取街道
  getStreet(param) {
    let that = this;
    let urlStr = "";
    urlStr += app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              districtFieldShow: true,
            });
          } else {
            that.setData({
              districtFieldShow: false,
            });
          }
        } else {
          that.setData({
            districtFieldShow: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      addressShow: false,
    });
  },
  tips(msg) {
    wx.showToast({
      icon: "none",
      title: msg,
    });
    return false;
  },
});
